﻿using movie.tool.library.hash;
using System;
using System.IO;

namespace movie.tool.library.utils
{
    public class FileUtils
    {
        /// <summary>
        /// 复制文件到目标目录。如果源目录已经在目标目录下(或者其子目录下)，则直接返回源目录
        /// </summary>
        /// <param name="filePath">复制的文件源目录</param>
        /// <param name="targetRoot">目标的根目录</param>
        /// <param name="targetParent">文件在目标根目录下的子目录</param>
        /// <returns></returns>
        public static string Copy(string filePath, string targetRoot, string targetParent)
        {
            string path;
            if (filePath.StartsWith(targetRoot))
            {
                //选择的文件在项目目录下,那就不用复制了
                path = filePath;
            }
            else
            {
                path = Path.Combine(targetRoot, targetParent);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path = Path.Combine(path, Path.GetFileName(filePath));
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                File.Copy(filePath, path);
            }
            return path;
        }

        public static string Copy(string filePath, string targetRoot, bool delExist, params string[] targetDir)
        {
            string path;
            if (filePath.StartsWith(targetRoot))
            {
                //选择的文件在项目目录下,那就不用复制了
                path = filePath;
            }
            else
            {
                path = targetRoot;
                foreach (string dir in targetDir)
                {
                    path = Path.Combine(path, dir);
                }
                
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                path = Path.Combine(path, Path.GetFileName(filePath));
                if (File.Exists(path))
                {
                    string selectDigest = SHA1Hash.FileDigest(filePath);
                    string targetDigest = SHA1Hash.FileDigest(path);
                    if (!selectDigest.Equals(targetDigest))
                    {
                        if (delExist)
                        {
                            File.Delete(path);
                            File.Copy(filePath, path);
                        }
                        else
                        {
                            throw new ApplicationException("文件" + path + "已经存在,无法复制,请选择不同名称的文件");
                        }
                    }
                }
                else
                {
                    File.Copy(filePath, path);
                }
            }
            return path;
        }
    }
}
